package com.zhangchuchu.neohealth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangchuchu.neohealth.common.R;
import com.zhangchuchu.neohealth.entity.Goods;
import com.zhangchuchu.neohealth.service.GoodsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * (Goods)控制层
 *
 * @author makejava
 * @since 2025-04-12 09:49:49
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    private GoodsService goodsService;

    /**
     * 查询所有数据（不分页）
     */
    @GetMapping("/getList")
    public R<List<Goods>> selectList() {
        return R.success(goodsService.list());
    }
    /**
     * 条件查询
     */
    @GetMapping("/searchList")
    public R<Page<Goods>> selectList(@RequestParam(value = "query", required = false) String query,@RequestParam int page, @RequestParam int size) {

        Page<Goods> page1 = new Page<>(page,size);
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();

        // 如果查询条件存在，则加入查询条件
        if (query != null && !query.trim().isEmpty()) {
            queryWrapper.like("name", query)  // 假设根据标题进行模糊查询
                    .or().like("content", query);  // 也可以根据内容进行模糊查询
        }
        return R.success(goodsService.page(page1,queryWrapper));
    }
    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @return 所有数据
     */
    @GetMapping()
    public R selectAll(@RequestParam int page, @RequestParam int size, Goods Goods) {
        Page<Goods> pageObj = new Page<>(page, size);
        return R.success(this.goodsService.page(pageObj, new QueryWrapper<>(Goods)));
    }
    /**
     * 通过主键查询单条数据
     */
    @GetMapping("{id}")
    public R<Goods> selectOne(@PathVariable Serializable id) {
        return R.success(goodsService.getById(id));
    }

    /**
     * 新增数据
     */
    @PostMapping
    public R<Boolean> insert(@RequestBody Goods goods) {
        return R.success(goodsService.save(goods));
    }

    /**
     * 修改数据
     */
    @PutMapping
    public R<Boolean> update(@RequestBody Goods goods) {
        return R.success(goodsService.updateById(goods));
    }

    /**
     * 删除数据（批量）
     */
    @DeleteMapping
    public R<Boolean> delete(@RequestParam("idList") List<Integer> idList) {
        return R.success(goodsService.removeByIds(idList));
    }

    /**
     * 兑换商品
     */
    @GetMapping("/exchange")
    public R<String> exchangeGoods(@RequestParam("userId") Integer userId, @RequestParam("id") Integer goodsId) {
        try {
            goodsService.exchangeGoods(userId, goodsId);
            return R.success("兑换成功");
        } catch (RuntimeException e) {
            return R.error("兑换失败：" + e.getMessage());
        }
    }

}
